package com.ridbor001.demo.servlet;

import com.ridbor001.demo.bean.RDBStudent;
import com.ridbor001.demo.bean.RDBTeacher;
import com.ridbor001.demo.bean.RDBUser;
import com.ridbor001.demo.service.RDBStudentService;
import com.ridbor001.demo.service.RDBTeacherService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RDBRegisterServlet extends HttpServlet {
    RDBStudentService rdbStudentService = new RDBStudentService();
    RDBTeacherService rdbTeacherService = new RDBTeacherService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws  IOException {
        request.setCharacterEncoding("UTF-8");
        String role = request.getParameter("role");
        System.out.println(role);

        try {
            RDBUser user = createUser(request, role);
            validateUser(user);
            saveUser(user);
            request.getSession().setAttribute("user", user);
            request.getSession().removeAttribute("errorMessage");
            response.sendRedirect("/rDBLogin.jsp");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
            request.getSession().setAttribute("errorMessage", e.getMessage());
            response.sendRedirect("rDBRegister.jsp");
        }catch (Exception e) {
            System.out.println(e.getMessage());
            request.getSession().setAttribute("errorMessage", "系统错误：" + e.getMessage());

        }
    }

    private RDBUser createUser(HttpServletRequest req, String role) {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String gender = req.getParameter("gender");
        int age = Integer.parseInt(req.getParameter("age"));
        String phone = req.getParameter("phone");

        if ("student".equals(role)) {
            return new RDBStudent(
                    name, password, gender, age, phone,
                    req.getParameter("studentId"),
                    req.getParameter("className"),
                    req.getParameter("major")
            );
        } else {
            return new RDBTeacher(
                    name, password, gender, age, phone,
                    req.getParameter("teacherId")
            );
        }
    }

    private void validateUser(RDBUser user) throws SQLException {
        if (user instanceof RDBStudent) {
            RDBStudent s = (RDBStudent) user;
            // 检查学号是否已存在
            if (rdbStudentService.studentExists(s.getStudentId())) {
                throw new IllegalArgumentException("学号已存在");
            }
        } else {
            RDBTeacher t = (RDBTeacher) user;
            // 检查教师ID是否已存在
            if (rdbTeacherService.teacherExists(t.getTeacherId())) {
                throw new IllegalArgumentException("教师ID已存在");
            }
        }

        // 验证其他字段（可选）
        if (user.getName() == null || user.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("姓名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (user.getAge() <= 0) {
            throw new IllegalArgumentException("年龄必须大于0");
        }
    }

    private void saveUser(RDBUser user) throws SQLException {
        if (user instanceof RDBStudent) {
            rdbStudentService.addStudent((RDBStudent) user);
        } else {
            rdbTeacherService.addTeacher((RDBTeacher) user);
        }
    }

}
